package top.kiterunner.learning.concurrency_test;

import java.time.LocalTime;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/22.
 */
public class ThreadDemo13 {

    private Lock lock = new ReentrantLock();

    public void t1() {
        synchronized (this) {
            LocalTime now = LocalTime.now();
            System.out.println(now + " " + Thread.currentThread().getName() + " Get Lock");
            /*try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                //e.printStackTrace();
                System.out.println(LocalTime.now() + " Catch Interruptable Exception.");
            }*/
            int k = 0;
            while(!Thread.interrupted()) {
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    System.out.println(LocalTime.now() + " Catch Interruptable Exception.");
                }
            }
            System.out.println(Thread.currentThread().getName() + " Game Over.");
        }
    }

    public void t2() {
        try {
            lock.lockInterruptibly();
            System.out.println(LocalTime.now() + " " + Thread.currentThread().getName() + " Get Lock");
            //TimeUnit.SECONDS.sleep(10);
            while (true) {
            }
        } catch (Exception e) {
            System.out.println(LocalTime.now() + " Catch Interruptable Exception.");
        } finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        ThreadDemo13 t13 = new ThreadDemo13();

        Thread thread1 = new Thread(t13::t2, "Thread_1");
        thread1.start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread thread2 = new Thread(t13::t2, "Thread_2");
        thread2.start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        thread1.interrupt();
        System.out.println("Thread2 status: " + thread2.isInterrupted());
    }
}
